package cn.jjxx.modules.sys.controller;

import cn.jjxx.core.common.data.DuplicateValid;
import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.model.PageJson;
import cn.jjxx.core.model.ValidJson;
import cn.jjxx.core.query.annotation.PageableDefaults;
import cn.jjxx.core.query.data.PageImpl;
import cn.jjxx.core.query.data.Pageable;
import cn.jjxx.core.query.data.PropertyPreFilterable;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.utils.QueryableConvertUtils;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.modules.sys.entity.SysHomePageManageUser;
import cn.jjxx.modules.sys.service.ISysHomePageManageUserService;
import cn.jjxx.modules.sys.service.IUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.baomidou.mybatisplus.annotations.TableName;

import org.framework.superutil.thirdparty.excel.ExcelDataFormatter;
import org.framework.superutil.thirdparty.excel.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import cn.jjxx.core.common.controller.BaseBeanController;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresPathPermission;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.framework.superutil.thirdparty.excel.ExcelUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import cn.jjxx.modules.common.bean.UploadExcel;
import cn.jjxx.modules.sys.entity.User;
import cn.jjxx.modules.sys.utils.UserUtils;
import cn.jjxx.core.config.BillConfig;
import cn.jjxx.modules.sys.entity.SysHomepageManage;
import cn.jjxx.modules.sys.service.ISysHomepageManageService;
import cn.jjxx.modules.map.service.ICommonMapService;

/**
 * @author zcg
 * @version V1.0
 * @Title: 首页管理
 * @Description: 首页管理
 * @date 2018-12-07 16:56:31
 */
@Controller
@RequestMapping("${admin.url.prefix}/sys/syshomepagemanage")
@RequiresPathPermission("sys:syshomepagemanage")
public class SysHomepageManageController extends BaseBeanController<SysHomepageManage> {

    @Autowired
    protected ISysHomepageManageService sysHomepageManageService;
    @Autowired
    protected ICommonMapService commonMapService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private ISysHomePageManageUserService iSysHomePageManageUserService;

    /**
     * @param id 主键Id.<br>
     * @Description: 根据获取首页管理的实体数据 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    public SysHomepageManage get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return sysHomepageManageService.selectById(id);
        } else {
            return newModel();
        }
    }

    /**
     * @Description: 跳转至首页管理的列表界面 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    @RequiresMethodPermissions("list")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("list");
    }

    /**
     * @Description: 首页管理的列表界面获取列表结果 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    @RequestMapping(value = "ajaxList", method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")
    private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        EntityWrapper<SysHomepageManage> entityWrapper = new EntityWrapper<SysHomepageManage>(entityClass);
        propertyPreFilterable.addQueryProperty("id");
        // 预处理
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<SysHomepageManage> pagejson = new PageJson<SysHomepageManage>(sysHomepageManageService.list(queryable, entityWrapper));
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

    /**
     * @Description: 跳转至首页管理的添加界面 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model, HttpServletRequest request, HttpServletResponse response) {
        if (!model.containsAttribute("data")) {
            model.addAttribute("data", newModel());
        }
        return display("edit");
    }

    /**
     * @param sysHomepageManage 首页管理实体类.<br>
     * @Description: 新增首页管理的数据 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") SysHomepageManage sysHomepageManage, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(sysHomepageManage, request, response, result);
    }

    /**
     * @Description: 跳转至首页管理的更新界面 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
                         HttpServletResponse response) {
        SysHomepageManage sysHomepageManage = get(id);
        model.addAttribute("data", sysHomepageManage);
        return display("edit");
    }

    /**
     * @param sysHomepageManage 首页管理实体类.<br>
     * @Description: 修改首页管理的数据 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") SysHomepageManage sysHomepageManage, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(sysHomepageManage, request, response, result);
    }

    /**
     * @param sysHomepageManage 首页管理实体类.<br>
     * @Description: 执行保存首页管理的数据操作 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson doSave(SysHomepageManage sysHomepageManage, HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("保存成功");
        if (hasError(sysHomepageManage, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson.fail(errorMsg);
            } else {
                ajaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        try {
            if (StringUtils.isEmpty(sysHomepageManage.getId())) {
                sysHomepageManageService.insert(sysHomepageManage);
            } else {
                sysHomepageManageService.insertOrUpdate(sysHomepageManage);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

    /**
     * @param id 单据Id.<br>
     * @Description: 单条删除首页管理 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        TableName table = SysHomepageManage.class.getAnnotation(TableName.class);
        String tableName = table.value();
        String dbName = MessageUtils.getMessage("connection.dbname");
        try {
            List<String> ids = Arrays.asList(id.split(","));
            //得到被其他表引用的结果
            String quoteMsg = commonMapService.quoteMsg(dbName, tableName, ids);
            if (StringUtils.isNotEmpty(quoteMsg)) {
                ajaxJson.setMsg("删除失败," + quoteMsg);
                return ajaxJson;
            }
            sysHomepageManageService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

    /**
     * @param ids 单据Id集合.<br>
     * @Description: 执行保存首页管理的数据操作 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    @RequestMapping(value = "batch/delete", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("批量删除成功");
        TableName table = SysHomepageManage.class.getAnnotation(TableName.class);
        String tableName = table.value();
        String dbName = MessageUtils.getMessage("connection.dbname");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            //得到被其他表引用的结果
            String quoteMsg = commonMapService.quoteMsg(dbName, tableName, idList);
            if (StringUtils.isNotEmpty(quoteMsg)) {
                ajaxJson.setMsg("批量删除失败," + quoteMsg);
                return ajaxJson;
            }
            sysHomepageManageService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("批量删除失败");
        }
        return ajaxJson;
    }

    /**
     * @Description: 跳转至首页管理的查看界面 .<br>
     * @param:ids 单据Id.<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") String id, HttpServletRequest request,
                       HttpServletResponse response) {
        SysHomepageManage sysHomepageManage = get(id);
        model.addAttribute("data", sysHomepageManage);
        return display("edit");
    }

    /**
     * @param duplicateValid 校验实体类.<br>
     * @Description: 验证首页管理功能数据的唯一性 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31.<br>
     */
    @RequestMapping(value = "validate", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
        ValidJson validJson = new ValidJson();
        Boolean valid = Boolean.FALSE;
        try {
            EntityWrapper<SysHomepageManage> entityWrapper = new EntityWrapper<SysHomepageManage>(entityClass);
            valid = sysHomepageManageService.doValid(duplicateValid, entityWrapper);
            if (valid) {
                validJson.setStatus("y");
                validJson.setInfo("验证通过!");
            } else {
                validJson.setStatus("n");
                if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
                    validJson.setInfo(duplicateValid.getErrorMsg());
                } else {
                    validJson.setInfo("当前信息重复!");
                }
            }
        } catch (Exception e) {
            validJson.setStatus("n");
            validJson.setInfo("验证异常，请检查字段是否正确!");
        }
        return validJson;
    }


    /**
     * @param bills  单据Id集合.<br>
     * @param status 可操作状态.<br>
     * @Description: 得到可以被审核的单据 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31 .<br>
     */
    private List<String> getAllowOptBills(List<String> bills, String status) {
        EntityWrapper<SysHomepageManage> wrapper = new EntityWrapper<SysHomepageManage>();
        wrapper.in("id", bills);
        wrapper.eq("status", status);
        List<SysHomepageManage> list = sysHomepageManageService.selectList(wrapper);
        bills = new ArrayList<String>();
        for (SysHomepageManage bean : list) {
            bills.add(bean.getId());
        }
        return bills;
    }

    /**
     * @param bills     可以操作的Id集合.<br>
     * @param newStatus 被修改的状态设置值.<br>
     * @Description: 设置批量更新参数 .<br>
     * @author zcg .<br>
     * @date 2018-12-07 16:56:31 .<br>
     */
    private List<SysHomepageManage> setBacthUpdate(List<String> bills, String newStatus) {
        List<SysHomepageManage> list = new ArrayList<SysHomepageManage>();
        User user = UserUtils.getUser();
        if (bills.size() > 0) {
            list = sysHomepageManageService.selectBatchIds(bills);
            for (SysHomepageManage bean : list) {
                bean.setStatus(newStatus);
                if (newStatus.equals(String.valueOf(BillConfig.SAVE)) ||
                        newStatus.equals(String.valueOf(BillConfig.SUBMIT))) {
                }
            }
        }
        return list;
    }


    /**
     * @Description:打开绑定用户页面
     * @Author:shishengfeng
     * @CreateDate:2018/12/10 10:38
     */
    @RequestMapping(value = "toBindUser", method = RequestMethod.GET)
    public String toBindUser(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("toBindUser");
    }


    @RequestMapping(value = "ajaxListUserByOrg", method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")
    private void ajaxListUser(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                              HttpServletResponse response, String nodeId) throws IOException {

        String type = request.getParameter("type");
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        if (type != null && "1".equals(type)) {
            List<String> userIds = new ArrayList<>();
            EntityWrapper<SysHomePageManageUser> entityWrapper = new EntityWrapper<>();
            List<SysHomePageManageUser> list = iSysHomePageManageUserService.selectList(entityWrapper);
            if (list.size() > 0) {
                for (SysHomePageManageUser sysHomePageManageUser : list) {
                    if (sysHomePageManageUser != null) {
                        userIds.add(sysHomePageManageUser.getUserId());
                    }
                }
            }
            if (userIds.size() > 0) {
                wrapper.notIn("t.id", userIds);
            }
        } else if (type != null && "0".equals(type)) {
            List<String> userIds = new ArrayList<>();
            String homePageId = request.getParameter("homePageId");
            EntityWrapper<SysHomePageManageUser> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("home_page_id", homePageId);
            List<SysHomePageManageUser> list = iSysHomePageManageUserService.selectList(entityWrapper);
            if (list.size() > 0) {
                for (SysHomePageManageUser sysHomePageManageUser : list) {
                    if (sysHomePageManageUser != null) {
                        userIds.add(sysHomePageManageUser.getUserId());
                    }
                }
            }
            if (userIds.size() > 0) {
                wrapper.in("t.id", userIds);
            } else {
                userIds.add("");
                wrapper.in("t.id", userIds);
            }
        }

        propertyPreFilterable.addQueryProperty("id");
        wrapper.setTableAlias("t.");
        List<String> orgIds = null;
        if (UserUtils.getUser().getAdminType().equals(User.ADMIN_NORMAL)) {//如果是系统用户则不过滤
            orgIds = UserUtils.getOrgChilds(true, true);
        }
        // 预处理
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        Pageable pageable = queryable.getPageable();
        com.baomidou.mybatisplus.plugins.Page<User> page = new com.baomidou.mybatisplus.plugins.Page<User>(pageable.getPageNumber(), pageable.getPageSize());
        com.baomidou.mybatisplus.plugins.Page<User> pageList = iUserService.selectUserListByPage(page, wrapper, nodeId, orgIds);
        PageJson<User> pagejson = new PageJson<User>(new PageImpl<User>(pageList.getRecords(), queryable.getPageable(), pageList.getTotal()));
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

    @RequestMapping(value = "toSaveBind", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson toSaveBind(@RequestParam(value = "ids", required = false) String[] ids, HttpServletRequest request,
                               HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("关联成功!");
        String homePageId = request.getParameter("homePageId");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            ajaxJson = sysHomepageManageService.toSaveBind(idList, homePageId);

        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("关联失败!");
        }
        return ajaxJson;
    }

    @RequestMapping(value = "toCancelUser", method = RequestMethod.GET)
    public String toCancelUser(Model model, HttpServletRequest request, HttpServletResponse response) {
        String homePageId = request.getParameter("homePageId");
        model.addAttribute("homePageId", homePageId);
        return display("toCancelUser");
    }


    @RequestMapping(value = "toSaveCancel", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson toSaveCancel(@RequestParam(value = "ids", required = false) String[] ids, HttpServletRequest request,
                                 HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("取消成功!");
        String homePageId = request.getParameter("homePageId");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            ajaxJson = sysHomepageManageService.toSaveCancel(idList, homePageId);

        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("取消失败!");
        }
        return ajaxJson;
    }

    @RequestMapping(value = "toSetDefault", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson toSetDefault(String id, HttpServletRequest request,
                                 HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("设置成功!");
        try {
            ajaxJson = sysHomepageManageService.toSetDefault(id);

        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("设置失败!");
        }
        return ajaxJson;
    }
}
